from setuptools import setup
import os, glob

def find_libffi():
  # Allow use custom env variables
  env = os.environ.get("LIBFFI_DYLIB")
  if env and os.path.exists(env):
    return env

  # Homebrew (Apple Silicon / Intel)
  candidates = [
    "/opt/homebrew/opt/libffi/lib/libffi.8.dylib",
    "/usr/local/opt/libffi/lib/libffi.8.dylib",
  ]

  # Python.org Framework
  for ver in ("3.13", "3.12", "3.11"):
    candidates.append(f"/Library/Frameworks/Python.framework/Versions/{ver}/lib/libffi.8.dylib")

  # Conda/Mamba
  for base in (
    os.environ.get("CONDA_PREFIX"),
    os.path.expanduser("~/anaconda3"),
    os.path.expanduser("~/miniconda3"),
    os.path.expanduser("~/mambaforge"),
  ):
    if base:
      candidates.append(os.path.join(base, "lib", "libffi.8.dylib"))
      candidates += glob.glob(os.path.join(base, "pkgs", "libffi-*/lib/libffi.8.dylib"))

  for p in candidates:
    if p and os.path.exists(p):
      return p
  return None

def find_openssl():
    env_dir = os.environ.get("OPENSSL_DYLIB_DIR")  # Optional: Allow use env specified directory
    candidates = []
    if env_dir:
        candidates += [
            os.path.join(env_dir, "libssl.3.dylib"),
            os.path.join(env_dir, "libcrypto.3.dylib"),
        ]

    # Homebrew (Apple Silicon / Intel)
    candidates += [
        "/opt/homebrew/opt/openssl@3/lib/libssl.3.dylib",
        "/opt/homebrew/opt/openssl@3/lib/libcrypto.3.dylib",
        "/usr/local/opt/openssl@3/lib/libssl.3.dylib",
        "/usr/local/opt/openssl@3/lib/libcrypto.3.dylib",
    ]

    return [p for p in candidates if os.path.exists(p)]

def main():
  ENTRY_POINT = ['main.py']
  OPTIONS = {
    'resources': ['web'],
    'argv_emulation': False,
    'strip': True,
    'iconfile': 'icon.png',
    'includes': [
      'webview',
      'pyautogui',
      'playwright.sync_api',
      'rubicon.objc',  # Use sub-module, don't use rubicon
      'objc',
    ],
    'packages': ['objc', 'webview'],
    'compressed': False,
    'site_packages': True,
    'excludes': [
      'wheel', 'setuptools', 'pkg_resources',
      'rubicon',  # ★ Important: Exclude rubicon
    ],
  }

  fwks = []  # add more if show lib missed when running packed app from terminal
  _OPENSSL = find_openssl()
  _LIBFFI = find_libffi()
  if _LIBFFI:
    fwks.append(_LIBFFI)
  if _OPENSSL:
      fwks.extend(_OPENSSL)
  if fwks:
    OPTIONS['frameworks'] = fwks

  setup(
    app=ENTRY_POINT,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
  )

if __name__ == "__main__":
  main()